package com.manager.web.system;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.manager.base.BaseAction;
import com.manager.pojo.system.SysMenu;
import com.manager.util.CONSTANT;
import com.manager.util.DateUtil;
import com.manager.util.Log;
import com.opensymphony.xwork2.Action;

public class SysMenuAction extends BaseAction {
	private SysMenu sysMenu;
	
	/*
	 * 添加左边栏菜单
	 */
	public String addMenu(){
		int loginUserId = super.getLoginUserId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//查询菜单名是否已存在
			int total = super.baseService.queryInt("select count(1) from sys_menu where name = ?", sysMenu.getName());
			if(total == 1){
				p.print("{\"flag\":false,\"msg\":\"该菜单名已存在\"}");
			}else{
				int nextSortNum = Integer.parseInt(request.getParameter("nextSortNum"));
				
				//调整其它所有比nextSortNum小的排序号
				if(sysMenu.getSortNum() < nextSortNum){
					//将此菜单的sortNum -1至指定的sortNum的序号依次加1
					Object[] params = new Object[4];
					params[0] = loginUserId;
					params[1] = DateUtil.getCurrentDateTime(true);
					params[2] = sysMenu.getSortNum();
					params[3] = nextSortNum - 1;
					super.baseService.update("update sys_menu set sort_num = sort_num + 1, update_by_id = ?, update_date_time = ? where sort_num between ? and ?", params);
				}
				
				//更新此菜单排序号并保存
				SysMenu sm = new SysMenu();
				sm.setName(sysMenu.getName());
				sm.setSortNum(sysMenu.getSortNum());
				sm.setCreateById(loginUserId);
				sm.setCreateDateTime(DateUtil.getCurrentDateTime(true));
				sm.setUpdateById(loginUserId);
				sm.setUpdateDateTime(DateUtil.getCurrentDateTime(true));
				super.baseService.save(sm);
				
				p.print("{\"flag\":true}");
			}
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 删除左边菜单
	 */
	public String deleteMenu(){
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//永远不允许删除"临时菜单"
			if(sysMenu.getId() == 2){
				p.write("{\"flag\":false,\"msg\":\"永远不允许删除--临时管理\"}");
			}else{
				//删除菜单
				super.baseService.delete("delete from sys_menu where id = ?", sysMenu.getId());
				//将大于该菜单sort_num的其它菜单的sort_num全减1
				super.baseService.update("update sys_menu set sort_num = sort_num - 1 where sort_num > ?", sysMenu.getSortNum());
				//将该菜单其下的所有权限的menu_id置为2(临时菜单)
				super.baseService.update("update sys_privilege set menu_id = 2 where menu_id = ?", sysMenu.getId());
				
				p.write("{\"flag\":true}");
			}
		}catch(Exception e){
			p.write("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 由id查询menu
	 */
	public String queryMenuById(){
		int sysMenuId = sysMenu.getId();
		String hql = "FROM SysMenu m WHERE m.id = ?";
		SysMenu sysMenu = (SysMenu)super.baseService.getObject(SysMenu.class, sysMenuId);
		this.sysMenu = sysMenu;
		super.forward("system/menuUpdate.jsp");
		return Action.NONE;
	}
	
	/*
	 * 更新menu
	 */
	public String updateMenu(){
		int loginUserId = super.getLoginUserId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//查询除了该ID的菜单，其它的所有菜单中该菜单名是否存在
			int total = super.baseService.queryInt("select count(1) from sys_menu where name = ? and id != ?", sysMenu.getName(), sysMenu.getId());
			if(total == 1){
				p.print("{\"flag\":false,\"msg\":\"该菜单名已存在\"}");
			}else{
				int oldSortNum = super.baseService.queryInt("select sort_num from sys_menu where id = ?", sysMenu.getId());
				
				//调整其它所有排序号
				if(sysMenu.getSortNum() > oldSortNum){
					//将此菜单的sortNum + 1至指定的sortNum的序号依次减1
					Object[] params = new Object[4];
					params[0] = loginUserId;
					params[1] = DateUtil.getCurrentDateTime(true);
					params[2] = oldSortNum + 1;
					params[3] = sysMenu.getSortNum();
					super.baseService.update("update sys_menu set sort_num = sort_num - 1, update_by_id = ?, update_date_time = ? where sort_num between ? and ?", params);
				}else if(sysMenu.getSortNum() < oldSortNum){
					//将此菜单的sortNum -1至指定的sortNum的序号依次加1
					Object[] params = new Object[4];
					params[0] = loginUserId;
					params[1] = DateUtil.getCurrentDateTime(true);
					params[2] = sysMenu.getSortNum();
					params[3] = oldSortNum - 1;
					super.baseService.update("update sys_menu set sort_num = sort_num + 1, update_by_id = ?, update_date_time = ? where sort_num between ? and ?", params);
				}
				
				//更新此菜单排序号
				SysMenu sm = (SysMenu)super.baseService.getObject(SysMenu.class, sysMenu.getId());
				sm.setName(sysMenu.getName());
				sm.setSortNum(sysMenu.getSortNum());
				sm.setUpdateById(super.getLoginUserId());
				sm.setUpdateDateTime(DateUtil.getCurrentDateTime(true));
				
				super.baseService.update(sm);
				
				p.print("{\"flag\":true}");
			}
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 更新menu
	 */
	public String updateSortNum(){
		int loginUserId = super.getLoginUserId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			int oldSortNum = super.baseService.queryInt("select sort_num from sys_menu where id = ?", sysMenu.getId());
			
			//调整其它所有排序号
			if(sysMenu.getSortNum() > oldSortNum){
				//将此菜单的sortNum + 1至指定的sortNum的序号依次减1
				Object[] params = new Object[4];
				params[0] = loginUserId;
				params[1] = DateUtil.getCurrentDateTime(true);
				params[2] = oldSortNum + 1;
				params[3] = sysMenu.getSortNum();
				super.baseService.update("update sys_menu set sort_num = sort_num - 1, update_by_id = ?, update_date_time = ? where sort_num between ? and ?", params);
			}else if(sysMenu.getSortNum() < oldSortNum){
				//将此菜单的sortNum -1至指定的sortNum的序号依次加1
				Object[] params = new Object[4];
				params[0] = loginUserId;
				params[1] = DateUtil.getCurrentDateTime(true);
				params[2] = sysMenu.getSortNum();
				params[3] = oldSortNum - 1;
				super.baseService.update("update sys_menu set sort_num = sort_num + 1, update_by_id = ?, update_date_time = ? where sort_num between ? and ?", params);
			}
			
			//更新此菜单排序号
			super.baseService.update("update sys_menu set sort_num = ? where id = ?", sysMenu.getSortNum(), sysMenu.getId());
			
			p.print("{\"flag\":true}");
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 查询所有的menu，提供给jquery filetree使用
	 */
	public String queryMenuAll(){
		String root = request.getParameter("jqueryFiletreeId");
		PrintWriter p = null;
		StringBuffer sb = new StringBuffer();
		String sql = null;
		
		try{
			p = response.getWriter();
			
			if(root.equals("source")){
				sql = "select id, name from sys_menu order by id desc";
			}else{
				p.flush();
				p.close();
				return Action.NONE;
			}
			
			List list = this.baseService.queryList(sql);
			
			if(list.size() > 0){
				sb.append("<ul class=\"jqueryFileTree\" style=\"display: none;\">");
				for(int i = 0; i < list.size(); i++){
					Map m = (Map)list.get(i);
					
					sb.append("<li class=\"directory collapsed\">");
						sb.append("<input type=\"checkbox\" style=\"display:none;\" value=\"" + m.get("id").toString() + "\"/>");
						sb.append("<a href=\"#\" rel=\"" + m.get("id").toString() + "\">" + m.get("name").toString() + "</a>");
					sb.append("</li>");
					
				}
				sb.append("</ul>");
				Log.info("menuAll:" + sb.toString());
				p.print(sb.toString());
			}else{
				p.print("error!!");
			}
			
		}catch(Exception e){
			p.print("error!!");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 查询所有的menu，提供给下拉框使用
	 */
	public String queryMenuAll2(){
		PrintWriter p = null;
		StringBuffer sb = new StringBuffer();
		
		try{
			p = response.getWriter();
			
			List<Map> list = super.baseService.queryList("select id, name from sys_menu order by id desc");
			Map m = null;
			
			sb.append("<option value=\"\">全部</option>");
			if(list != null && list.size() > 0){
				for(int i = 0; i < list.size(); i++){
					m = list.get(i);
					sb.append("<option value=\"").append(m.get("id").toString()).append("\">");
					sb.append(m.get("name").toString());
					sb.append("</option>");
				}
			}
			
			p.print(sb.toString());
		}catch(Exception e){
			p.print("erro!!");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 取得下一个排序号
	 */
	public String queryNextSortNum(){
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			int nextSortNum = super.baseService.queryInt("select count(1) from sys_menu") + 1;
			
			p.print("{\"flag\":true,\"nextSortNum\":\"" + nextSortNum + "\"}");
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * getter and setter
	 */
	public SysMenu getSysMenu() {
		return sysMenu;
	}
	
	public void setSysMenu(SysMenu sysMenu) {
		this.sysMenu = sysMenu;
	}
}
